package BIO.tcp;
/*
 * @Author  Wrial
 * @Date Created in 22:45 2020/4/8
 * @Description TCPServer
 */

import java.io.*;
import java.net.*;

public class TCPServer {

    public static void main(String[] args) throws IOException {
        TCPServer tcpServer = new TCPServer(8090);
        tcpServer.service();
    }

    private ServerSocket serverSocket;

    public TCPServer(int port) throws IOException {
        init(port);
    }

    private void init(int port) throws IOException {
        serverSocket = new ServerSocket(port);
        System.out.println("server init ——> " + serverSocket.getInetAddress().getHostAddress()  + "port :"+  port);
    }

    private String serverReceiveAndEcho(String msg) {
        System.out.println("Receive :" + msg);
        return "echo from server :" + msg;
    }


    private PrintWriter getWriter(Socket socket) throws IOException {
        return new PrintWriter(socket.getOutputStream(),true);
    }

    private BufferedReader getReader(Socket socket) throws IOException {
        return new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    public void service() throws IOException {
        Socket accept;
        while (true) {
            accept = serverSocket.accept();
            System.out.println("client :" + accept.getInetAddress().getHostName() + "已经连接");

            BufferedReader bufferedReader = getReader(accept);
            PrintWriter printWriter = getWriter(accept);

            String msg;
            while ((msg = bufferedReader.readLine()) != null) {
                printWriter.println(serverReceiveAndEcho(msg));
                if (msg.equals("end")){
                    break;
                }
            }
            try {
                if (accept!=null) accept.close();
                if (bufferedReader!=null) bufferedReader.close();
                if (printWriter!=null) printWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
